package com.base.cn.platform.os.service.manage.join;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.manage.join.SysRoleFunctionDao;
import com.base.cn.platform.os.entity.manage.join.SysRoleFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 角色和权限资源关联业务类
 *
 * @author s.li
 * @create 2018-02-05 16:33
 */
@Service
public class SysRoleFunctionBiz extends BaseBiz<SysRoleFunction,SysRoleFunctionDao> {

    @Autowired
    private SysRoleSubjectBiz sysRoleSubjectBiz;

    /**
     * 保存角色的操作权限和内容权限
     * @param functionIds 角色ID
     */
    @Transactional(rollbackFor = IllegalArgumentException.class )
    public void saveSysRoleFunctionSubject(BigDecimal roleId,String functionIds){
        //删除原有的权限
        this.deleteWhereSql(" roleId="+roleId);
        if(StringUtils.isNotEmpty(functionIds)){//添加现有的权限
            Set<String> set = new HashSet<>();
            Arrays.stream(functionIds.split(",")).forEach(str->{
                if(StringUtils.isNotEmpty(str)){
                    set.add(str);
                }
            });
            if(ObjectUtils.isNotEmpty(set)){
                List<SysRoleFunction> roleFunctionList = new ArrayList<>();
                set.forEach(functionId->{
                    SysRoleFunction roleFunction = new SysRoleFunction();
                    roleFunction.setRoleId(roleId);
                    roleFunction.setFunctionId(new BigDecimal(functionId));
                    roleFunctionList.add(roleFunction);
                });
                if(ObjectUtils.isNotEmpty(roleFunctionList)){
                    this.batchSave(roleFunctionList);
                }
            }
        }
    }

    /**
     * 通过角色ID串，查询角色关联的资源列表数据
     * @param roleIds 角色ID串
     * @return 角色与资源权限关联的数据列表
     */
    public List<SysRoleFunction> findSysRoleFunctionListByRoleIds(String roleIds){
        return this.find(" roleId in ("+roleIds+")",null,null);
    }
}
